import {messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import config from 'config'
import httpFetch from 'share/httpFetch'
import paymentService  from 'containers/pay/pay-workbench/pay-workbench.service'
import { Form, InputNumber, Icon, Tooltip, Select, Spin, Popover, Timeline, message } from 'antd'
const Option = Select.Option;

import moment from 'moment'

class EditableCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
      payType: "",
      modifyValue: null,
      editable: false,
      array: [],
      fetching: false,
      historyContent: null,
      historyLoading: false,
      selectItem: {}
    }
  }

  componentWillMount() {
    this.setState({
      value: this.props.value,
      payType: this.props.payType
    })
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.value !== this.props.value){
      this.setState({ value: nextProps.value });
      console.log(nextProps)
    }

  }


  //确认修改
  check = (e) => {
    const { value, selectItem } = this.state;
    e.stopPropagation();
    this.props.onChange(value, selectItem);
    setTimeout(() => {
      !this.props.onChangeError && this.setState({ editable: false, modifyValue: this.state.value })
    })
  };

  //取消修改
  cancel = (e) => {
    e.stopPropagation();
    this.setState({
      editable: false,
      value: this.state.modifyValue || this.props.value
    })
  };

  //获取支付类型
  getPayType = () =>{
    this.setState({ fetching: true });
    this.getSystemValueList(2105).then(response =>{
      let array = [];
      response.data.values.map(item=>{
        array.push({key: item.value, label: item.messageKey})
      });
      this.setState({ array, fetching: false })
    })
  };

  //获取收款账号
  getAccountOptions = () => {
    let url = `${config.baseUrl}/api/DepartmentGroup/selectBankInfo?partnerId=${this.props.record.partnerId}&partnerCategory=${this.props.record.partnerCategory}`;
    this.setState({ fetching: true });
    httpFetch.get(url).then(res => {
      if (res.status === 200) {
        let array = [];
        res.data.map(item=>{
          array.push(Object.assign(item, { key: item.accountNumber, label: item.viewName }));
        });
        this.setState({ array, fetching: false })
      }
    }).catch(() => {
      message.error(messages('pay.key1'/*收款账号获取失败*/));
      this.setState({ fetching: false })
    })
  };

  //显示支付历史
  payHistory = (visible) => {
    const { record } = this.props;
    if (visible) {
      this.setState({ historyLoading: true });
      paymentService.showPayHistory(this.props.record.id).then(res => {
        if (res.status === 200) {
          let historyContent;
          if (res.data.length) {
            historyContent = (
              <Timeline>
                {res.data.map(item => {
                  return (
                    <Timeline.Item key={item.id} color="green">
                      <span style={{fontSize:13,color:'rgba(0,0,0,0.55)',marginRight:5}}>{moment(item.createdDate).format('YYYY-MM-DD HH:mm:ss')}</span>
                      {item.employeeId} {item.employeeName} {item.operationType === 'payment' ? messages('pay.key2'/*支付*/) : item.operationType ==='return'? messages('pay.key3'/*退款*/):messages('pay.key4'/*反冲*/)} {item.currency}
                      {(item.amount || 0).toFixed(queryCurrencyPrecision(record.currency)).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')}
                    </Timeline.Item>
                  )
                })}
              </Timeline>
            )
          } else {
            historyContent = (
              <div>{messages('pay.key5'/*无支付历史*/)}</div>
            )
          }
          this.setState({ historyContent, historyLoading: false })
        }
      })
    }
  };

  handleSelectChange  = value => {
    const { array } = this.state;
    let selectItem = array.find(item => item.key === value) || {};
    this.setState({ value, selectItem })
  };

  render() {
    const { type, message, record, disable} = this.props;
    const { value, payType, editable, modifyValue, array, fetching, historyContent, historyLoading } = this.state;
    let history = (
      <Spin spinning={historyLoading}>
        {historyContent}
      </Spin>
    );
    return (
      <div className="editable-cell">
        {
          (editable && !disable) ?
            <div className="editable-cell-input-wrapper">
              {
                type === 'number' ?
                  <InputNumber value={value}
                               onChange={(value) => this.setState({ value })}/>
                  :
                  <Select defaultValue={value}
                          notFoundContent={fetching ? <Spin size="small" /> : messages('pay.key6'/*无匹配结果*/)}
                          onChange={this.handleSelectChange}
                          onFocus={payType=== "payType" ? this.getPayType : this.getAccountOptions}>
                    {array.map(option => {
                      return <Option key={option.key}>{option.label}</Option>
                    })}
                  </Select>
              }
              <Tooltip placement="top" title={messages('common.save')/*保存*/}>
                <Icon type="check" className="editable-cell-icon-check" onClick={this.check}/>
              </Tooltip>
              <Tooltip placement="top" title={messages('common.cancel')/*取消*/}>
                <Icon type="close" className="editable-cell-icon-cancel" onClick={this.cancel}/>
              </Tooltip>
            </div>
            :
            (
              type === 'number'? (
                <Popover placement="bottom" content={history} onVisibleChange={this.payHistory}>
                  <a className={`editable-cell-text-wrapper ${disable ? 'disable-cell-text-wrapper' : ''}`} style={{textAlign:'right'}}>
                    {modifyValue && modifyValue < this.props.value &&
                    <Tooltip title={messages('pay.key7'/*本次支付金额不等于可支付金额*/)}><Icon type="exclamation-circle-o" style={{color:'red',marginRight:5}} /></Tooltip>}
                    {(value || 0).toFixed(queryCurrencyPrecision(record.currency)).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')}
                    { !disable && (
                      <Tooltip placement="top" title={message}>
                        <Icon type="edit" className="editable-cell-icon" onClick={(e) => {e.stopPropagation();this.setState({ editable: true })}} />
                      </Tooltip>
                    ) }
                  </a>
                </Popover>
              ) : (
                <a className="editable-cell-text-wrapper">
                  {value}
                  <Tooltip placement="top" title={message}>
                    <Icon type="edit" className="editable-cell-icon" onClick={(e) => {e.stopPropagation();this.setState({ editable: true })}} />
                  </Tooltip>
                </a>
              )
            )
        }
      </div>
    );
  }
}

EditableCell.propTypes = {
  type: React.PropTypes.string,          //修改数据的类型，为 number、string
  value: React.PropTypes.any.isRequired, //默认值
  message: React.PropTypes.string,       //点击修改时的提示信息
  record: React.PropTypes.object,        //行信息
  onChange: React.PropTypes.func,        //确认修改时的回调
  onChangeError: React.PropTypes.bool,    //确认修改时的回调后是否出错
  disable: React.PropTypes.bool
};

EditableCell.defaultProps={
  type: 'string',
  message: messages('pay.key8'/*点击修改*/),
  record: {},
  onChange: () => {},
  onChangeError: false,
  disable: false
};

const WrappedEditableCell= Form.create()(EditableCell);

export default WrappedEditableCell;
